package com.controller;

import com.entity.Student;
import com.service.StudentService;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.tags.Param;

import java.util.List;

@Data
@RestController
@CrossOrigin
@RequestMapping("/student")
public class StudentController {
    @Autowired
    private StudentService studentService;

    private Result success(Object data) {
        return new Result(200, data);
    }

    private Result success(String msg) {
        return new Result(200, msg);
    }

    private Result fail(String msg) {
        return new Result(500, msg);
    }

    // 下面是具体的请求
    // 查询所有学生请求
    @GetMapping
    public Result selectAllStudents() {
        List<Student> students = studentService.selectAllStudents();
        return students != null && !students.isEmpty() ? success(students) : fail("无数据");
    }

    // 用 id 查询一个学生请求
    @GetMapping("/{id}")
    public Result selectAllStudents(@PathVariable String id) {
        Student student = studentService.selectOneStudentById(Integer.parseInt(id));
        return student != null ? success(student) : fail("无数据");
    }

    // 用 name 查询一个学生请求
    @GetMapping(params = "name")
    public Result selectOneStudentByName(String name) {
        List<Student> students = studentService.selectOneStudentByName(name);
        return students != null && !students.isEmpty() ? success(students) : fail("无数据");
    }

    // 新增一个学生请求
    @PostMapping
    public Result insertOneStudent(@RequestBody Student student) {
        int i = studentService.insertOneStudent(student);
        return i > 0 ? success("新增成功") : fail("新增失败");
    }

    // 修改一个学生请求
    @PutMapping
    public Result updateOneStudent(@RequestBody Student student) {
        int i = studentService.updateOneStudent(student);
        return i > 0 ? success("修改成功") : fail("修改失败");
    }

    // 删除一个学生请求
    @DeleteMapping("/{id}")
    public Result deleteOneStudent(@PathVariable String id) {
        int i = studentService.deleteOneStudent(Integer.parseInt(id));
        return i > 0 ? success("删除成功") : fail("删除失败");
    }


}
